<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Potevio集成平台</title>
</head>
<body>
    <div th:fragment="main" id="ssUser" class="container userControl">
        <link rel="stylesheet" th:href="@{css/organizationGroup/zTree/zTreeStyle/awesome.css}">
        <link rel="stylesheet" th:href="@{css/userGroup/userControl.css}">
        <div class="row">
            <div class="col-xs-12 operation">
                <div class="operation-content">
                    <div class="operation-header clearfix">
                        <form class="navbar-form" onsubmit="return false;">
                            <div class="groups form-group">
                                <span class="find">
                                    <i class="fa fa-search"></i>
                                </span> 
                                <input type="text" class="form-control search" id="search" placeholder="请输入用户登录名">
                            </div>
                            <input type="button" value="搜索" class="btn btn-primary nav-btn" id="searchUser">
                        </form>
                        <input id="fileupload" name="fileupload" type="file" style="display: none;" data-url="user/importSubSystemUser">
                        <a th:if="${#authorization.expression('hasAuthority(''createUser'')')}"  href="#platform-userGroup-ssUser" id="importSsUser" onclick="$('input[id=fileupload]').click();" class="addUser btn btn-primary nav-btn">导入用户</a>
                        <a href="#userGroup-ssUser" id="exportSsUser" class="addUser btn btn-primary nav-btn">导出用户</a>
                    </div>
                    <div class="operation-table" id="operation-table">
                        <table id="userList"></table>
                        <div id="gridpager"></div> 
                    </div>
                </div>
            </div>
        </div>
        <!--删除提示模态框  -->
        <div id="deleteNotice" class="modal fade bs-example-modal-sm notice" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel">
            <div class="modal-dialog modal-sm" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                        <h3 class="modal-title" id="myModalLabel">操作提示</h3>
                    </div>
                    <div class="modal-body">
                        确认删除此条数据吗？
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-primary" id="deleteData">确定</button>
                        <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
                </div>
            </div>
        </div>
        <script th:src="@{/assets/jqGrid/js/jquery.jqGrid.src.js}"></script>
        <script th:src="@{/assets/jqGrid/js/grid.locale-cn.js}"></script>
        <script th:src="@{/js/Map.js}"></script>
        <script th:src="@{/assets/jquerUi/jquery.ui.widget.js}"></script>
    	<script th:src="@{/assets/jquerUi/jquery.fileupload.js}"></script>
        <script th:inline="javascript">
            // jqgrid表格配置
            // 使jqgrid的宽和高自适应父元素
            var parentHeight,parentWidth;
            var subSystemMap = new Map();
            var hasDeleteUser = [[${#authorization.expression('hasAuthority(''deleteUser'')')}]];
        	// load subsystem
            $.ajax({
                url:contextPath + '/SubSystem/querySubSystem?page=1&size=9999',
                type:"get",
                contentType:"application/json",
                dataType:"json",
                data: data,
                async: false,
                success:function(data){
                	console.log(data);
                	var len = data.length;
                	for(var i = 0; i < len; i++) {
                		var d = data[i];
                		subSystemMap.put(d.id, d);
                	}
                },
                error:function(){
                    toastr.success('获取子系统信息失败！','操作失败');
                }
            });
         
            $(function(){ 
                //页面加载完成之后执行
                autodivheight();
                
                
                $('#fileupload').fileupload({
                	dataType: 'json',
                	done: function (e, data) {
                		if(data.result.code == "1") {
                			toastr.success('导入子系统用户成功！','操作成功');
                		} else if(data.result.code == "2") {
                			toastr.error(data.result.message,'操作失败');
                		} else {
                			toastr.success('导入子系统用户部分成功！','操作成功');
                		}
                		 $("#userList").trigger("reloadGrid");
                	}
                });
            });

            // 初始化jqGrid
            // 操作按钮
            function operation(cellvalue,options,rowObject){
                var amend = "";
                var deleted = "";
                if(hasDeleteUser) {
                	deleted = "<input style='margin:5px 3px' class='btn btn-danger btn-xs del' type='button' value='删除' title='删除' data-toggle='modal' data-target='.bs-example-modal-sm'>";
                }
                return amend+deleted;
            };
            // 用户角色显示
            function auth(authType){
                 return '子系统用户';
            }
            function formatSubSystem(ssysId) {
            	console.log("ssmap: " + subSystemMap);
            	console.log("get: " + ssysId);
            	if(subSystemMap.containsKey(ssysId)) {
            		var ss = subSystemMap.get(ssysId);
            		return ss.name;
            	}
            	return "未知子系统";
            }
            function rolesId(array) {
            	if(array == undefined || array == null) {
            		return "";
            	}
                var newArray = [];
                for(var i = 0,len = array.length; i < len; i++){
                    newArray[i] = array[i].id;
                }
                return newArray;
            }
            function pageInit(){
                //创建jqGrid组件
                jQuery("#userList").jqGrid({
                    datatype: "json",
                    url : contextPath + "/user/querySubSystemUserJqg",
                    height: parentHeight - 23,
                    width: parentWidth + 14,
                    colNames:['用户ID','登录名称','登录密码','用户名称', '用户类型','用户类型ID','角色类型','角色ID','用户头衔','所属组织机构','所属组织机构ID','所属组织机构内部编码','所属子系统','操作'],
                    colModel:[
                            {name:'id',index:'id', sorttype:"int",hidden:true},
                            {name:'username',index:'username'},
                            {name:'password',index:'password',sorttype:"string",hidden:true},
                            {name:'displayName',index:'displayName',sorttype:"string"},
                            {name:'authType',index:'authName',sortable: false,sorttype:"string",formatter: auth},
                            {name:'authType',index:'authType',sorttype:"string",hidden:true},
                            {name:'rolesName',index:'rolesName',sorttype:"string",hidden:true},
                            {name:'roles',index:'roles',sorttype:"string",formatter: rolesId,hidden:true},
                            {name:'title',index:'title', sortable: false,sorttype:"string"},
                            {name:'organizationName',index:'organizationName',sorttype:"string",hidden:true},
                            {name:'organizationId',index:'organizationId',sorttype:"string",hidden:true},
                            {name:'organizationCode',index:'organizationCode',sorttype:"string",hidden:true},
                            {name:'subSystem',index:'subSystem',sorttype:"string",formatter: formatSubSystem},
                            {name:'operation',index:'id', sortable: false,formatter: operation}
                    ],
                    sortname:'id',
                    sortorder:'asc',
                    viewrecords: true,
                    multiselect: true,
                    rowNum: 20,
                    rowList:[20,50,100],
                    pager:"#gridpager"
                });
                /*创建jqGrid的操作按钮容器*/
                jQuery("#userList").jqGrid('navGrid', '#gridpager', {edit: false,add: false, del:false,search: false});
            }; 
            //函数：获取尺寸
            function autodivheight(){
                parentHeight = $("#operation-table").height(),
                parentWidth = $("#operation-table").width();
                pageInit();
            }
            $(window).onresize = autodivheight; //浏览器窗口发生变化时同时变化DIV高度

            $(function(){　　 
                $(window).resize(function(){　
                    $(window).unbind("onresize");　
                    $("#userList").setGridWidth($('#operation-table').width()*1 + 12);　　
                    $("#userList").setGridHeight($('#operation-table').height()*1 - 23);　
                    $(window).bind("onresize", this);　
                });　　
            });
            // 侧边栏缩小时，实时的给jqgrid的宽和高赋值
            $("#asidebarSwitch").on('click',function() {
                var time = 0;
                var set = setInterval(function (){
                    $("#userList").setGridWidth($('#operation-table').width()*1 + 14);　　
                    $("#userList").setGridHeight($('#operation-table').height()*1 - 23);
                    time++;
                    if(time == 201){
                        clearInterval(set);
                    }
                },time);
            });

           
            // 搜索
            $("#searchUser").on('click',function () {
                var userName = $('#search').val();
                console.log(userName);
				// $.ajax({
                //     url: contextPath + "/user/getUserByName",
                //     type: "get",
				// 	data: {'name': userName},
                //     success: function(data){
                //         localData = [data];
                //         $("#userList").jqGrid('setGridParam', {
                //             // datatype : 'local',
                //             data : localData
                //         }).trigger("reloadGrid");
                //     },
                //     error: function(data){
                //         toastr.error("请求失败，请稍后再试!");
                //     }
                // });
                $("#userList").setGridParam({
                    url : contextPath + "/user/querySubSystemUserJqg",
                    postData : {
                        queryCond:{
                            username: userName
                        }
                    }
                }).trigger("reloadGrid");
                
            });
            $('#search').on('keypress',function(event){  
                var theEvent = window.event || event;
                var code = theEvent.keyCode || theEvent.which;
                var userName = $('#search').val();
                var localData;
                if(code == 13) {
                    $("#userList").setGridParam({
                        url : contextPath + "/user/querySubSystemUserJqg",
                        postData : {
                            queryCond:{
                                username: userName
                            }
                        }
                    }).trigger("reloadGrid");
                }
            });

            // 修改
            $("#userList").on('click','.revise',function(){
                var parentId = $(this).parent().parent().attr('id');
                var ids = $("#userList").jqGrid('getRowData',parentId);
                delete ids.operation;
                console.log('ids:'+JSON.stringify(ids));
                $.cookie('userData',JSON.stringify(ids));
            });

            // 删除
            var data,dataobj;
            // 获取数据
            $("#userList").on('click','.del',function(){
                var id = $(this).parent().parent().attr('id');
                var ids = $("#userList").jqGrid('getRowData',id);
                delete ids.operation;
                dataobj = ids;
            });
            // 点击删除
            $("#deleteData").on('click',function(){
                $.ajax({
                    url:contextPath + '/user/deleteSubSystemUser/' + dataobj.id,
                    type:"delete",
                    contentType:"application/json",
                    dataType:"json",
                    success:function(data){
                        if(data.code == 1){
                            $('#deleteNotice').modal('hide');
                            toastr.success('删除成功！','删除成功');
                            $("#userList").trigger("reloadGrid");
                        }else{
                            toastr.error('删除失败！','删除失败');
                        }
                    },
                    error:function(){
                        toastr.error('操作失败！','操作失败');
                    }
                });
            });
            
            $("#exportSsUser").on('click',function(){
				var url = "user/exportSubsystemUserList";
				window.open(url);
            });
        </script>
    </div>
</body>
</html>